package fair.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import fair.constant.RedisConstant;
import fair.dao.SetMealDao;
import fair.entity.PageResult;
import fair.pojo.CheckGroup;
import fair.pojo.Setmeal;
import fair.service.SetMealService;
import fair.utils.QiNiuUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fair_wu
 * @version v1.0
 * @date 2021-01-26 下午 13:05
 */

@Service(interfaceClass = SetMealService.class)
@Transactional
public class SetMealServiceImpl implements SetMealService {

    @Autowired
    private SetMealDao dao;

    @Autowired
    private JedisPool pool;

    @Autowired
    private FreeMarkerConfigurer freeMark;

    @Value("${out_put_path}")
    private String outPutPath;

    @Override
    public void add(Setmeal setmeal, Integer[] checkGroupIds) {
        dao.add(setmeal);
        if (checkGroupIds != null && checkGroupIds.length > 0)
            setCheckGroupAndSetMeal(setmeal.getId(), checkGroupIds);
        pool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());
        generateMobileStaticHtml();
    }

    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> page = dao.selectByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public void deleteById(Integer id) {
        Setmeal setmeal = dao.findById(id);
        String fileName = setmeal.getImg();
        QiNiuUtils.delete(fileName);
        pool.getResource().srem(RedisConstant.SETMEAL_PIC_RESOURCES, fileName);
        pool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES, fileName);
        dao.deleteCheckGroupIdBySetMealId(id);
        dao.deleteById(id);
        generateMobileStaticHtml();
    }

    @Override
    public void edit(Setmeal setmeal, Integer[] checkGroupIds) {
        dao.edit(setmeal);
        if (checkGroupIds != null && checkGroupIds.length > 0) {
          dao.deleteCheckGroupIdBySetMealId(setmeal.getId());
          setCheckGroupAndSetMeal(setmeal.getId(), checkGroupIds);
        }
        generateMobileStaticHtml();
    }

    @Override
    public List<Integer> findCheckGroupIdsBySetMealId(Integer id) {
        return dao.findCheckGroupIdsBySetMealId(id);
    }

    @Override
    public Setmeal findById(Integer id) {
        Setmeal setmeal = dao.findById(id);
        setmeal.setId(id);
        return setmeal;
    }

    @Override
    public List<Setmeal> findAll() {
        return dao.findAll();
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return dao.findSetmealCount();
    }

    private void setCheckGroupAndSetMeal(Integer setmealId, Integer[] checkGroupIds) {
        if (checkGroupIds != null && checkGroupIds.length > 0) {
            Map<String, Integer> map = null;
            for (Integer id : checkGroupIds) {
                map = new HashMap<>();
                map.put("checkgroup_id", id);
                map.put("setmeal_id", setmealId);
                dao.setCheckGroupAndSetMeal(map);
            }
        }
    }

    private void generateHtml(String templateName, String htmlPageName, Map<String, Object>map){
        Configuration configuration = freeMark.getConfiguration();
        Writer writer = null;
        try {
            Template template = configuration.getTemplate(templateName);
            File file;
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(outPutPath + htmlPageName)),"UTF-8"));
            template.process(map, writer);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //生成套餐列表静态页面
    private void generateMobileStaticHtml(){
        List<Setmeal> setmeals = dao.findAll();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(setmeals);
        //生成套餐详情静态页面（多个）
        generateMobileSetmealDetailHtml(setmeals);
    }

    private void generateMobileSetmealListHtml(List<Setmeal> setmeals) {
        Map<String, Object> map = new HashMap<>();
        map.put("setmealList", setmeals);
        this.generateHtml("mobile_setmeal.ftl", "m_setmeal.html", map);
    }
    private void generateMobileSetmealDetailHtml(List<Setmeal> setmeals) {
        for (Setmeal setmeal : setmeals) {
          Map<String, Object> map = new HashMap<>();
          map.put("setmeal", this.findById(setmeal.getId()));
          this.generateHtml("mobile_setmeal_detail.ftl", "m_setmeal_detail_"+setmeal.getId() + ".html", map);
        }
    }
}
